<template>
  <section>
     
    <!-- 面包屑 -->
     <breadcrumbs></breadcrumbs>
    <!-- 查询条件 -->
    <el-form ref="searchForm" :model="searchForm" label-width="100px" inline class="demo-form-inline" size="small" style="border-bottom: 1px solid #f6f6f6">
      <el-form-item label="文章标题" prop="key">
        <el-input v-model="searchForm.title" placeholder="请输入文章标题关键字"></el-input>
      </el-form-item>
      <el-form-item label="搜索时间段" prop="date">
        <el-date-picker v-model="searchForm.date" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="
            searchForm.current = 1;
            search();
          ">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <btns @exec="exec"></btns>
    <div class="data-container scroll-table">
      <div>
        <div class="ind-title lh50 f16">环保公益文章</div>
      </div>
      <el-table :data="tableData" style="width: 100%" row-key="dictId" border @selection-change="tableSelectionChange">
        <el-table-column type="selection" width="50"> </el-table-column>
        <el-table-column label="序号" prop="index" type="index" width="70px"></el-table-column>
        <el-table-column prop="epTypeId" label="分类名称">
          <template slot-scope="scope">
            <span v-for="(item,i) in fenleiname" :key='i' v-if="scope.row.epTypeId===item.epTypeId">{{item.typeName}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="文章标题"> </el-table-column>
        <el-table-column label="文章封面图">
          <template width="90" slot-scope="scope">
            <img style="width:120px;height:120px;border:none;" :src="scope.row.headImgUrl" />
          </template>
        </el-table-column>
        <el-table-column prop="isReferrer" label="排序" width="50"> </el-table-column>
        <el-table-column prop="addTime" label="发布时间"> </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <div type="primary" @click="goInfo(scope.row)">查看详情</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pages">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15, 20]"
                     :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="添加环保公益文章" :visible.sync="dialogCreateFormVisible">
      <el-form :model="createForm" label-width="120px" ref="createForm" :rules="rules">
        <el-form-item label="文章分类" prop="epTypeId">
          <el-select v-model="createForm.epTypeId" placeholder="请选择文章分类">
            <el-option v-for="(item,i) in fenleiname" :key='i' :label="item.typeName" :value="item.epTypeId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文章排序" prop="isReferrer">
          <el-input v-model="createForm.isReferrer" maxlength="25" type="number" show-word-limit autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="文章封面" prop="headImgUrl" :label-width="formLabelWidth">
          <el-upload :action="importFileUrl" v-model="createForm.headImgUrl" list-type="picture-card" :before-upload="beforeAvatarUpload" :auto-upload="true"
                     :on-success="getUrl" :accept="'image/*'" :show-file-list="false">
            <img v-if="hasFile" :src="createAddfile" class="img-feng" alt="图片" />
            <i v-else class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="createForm.title" maxlength="25" show-word-limit autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章详情" prop="content">
          <Editor ref="child" v-model="createForm.content" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBanner('createForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改公益文章" :visible.sync="dialogEditFormVisible">
      <el-form :model="EditForm" label-width="120px" ref="EditForm" :rules="rules">
        <el-form-item label="文章分类" prop="typeName">
          <el-select v-model="EditForm.epTypeId" placeholder="请选择文章分类">
            <el-option v-for="(item,i) in fenleiname" :key='i' :label="item.typeName" :value="item.epTypeId"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文章排序" prop="isReferrer">
          <el-input v-model="EditForm.isReferrer" maxlength="25" type="number" show-word-limit autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="文章封面" prop="headImgUrl" :label-width="formLabelWidth">
          <el-upload :action="importFileUrl" v-model="EditForm.headImgUrl" list-type="picture-card" :before-upload="beforeAvatarUpload" :auto-upload="true"
                     :on-success="geEdittUrl" :accept="'image/*'" :show-file-list="false">
            <img :src="EditAddfile" class="img-feng" alt="图片" />

          </el-upload>
        </el-form-item>
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="EditForm.title" maxlength="25" show-word-limit autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章详情" prop="content">
          <quill-editor v-model="EditForm.content" />
          <!-- <Editor ref="child" v-model="EditForm.content"/> -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editBanner('EditForm')">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import btns from "@/components/btns.vue";
import Editor from "@/components/edit";
import mixins from "@/utils/mixins";
import breadcrumbs from "@/components/breadcrumbs.vue";
export default {
  mixins: [mixins],
  components: {
    btns,
    Editor,
    breadcrumbs,
  },
  data() {
    var FengValidate = (rule, value, callback) => {
      // console.log(this.addfile);
      if (this.addfile == "") {
        callback(new Error("请选择封面图片"));
      }
      // if (value == null || value == '') {
      //   this.activeNames = ['2'];
      // }
    };
    return {
      addfile: "",
      fenleiname: [
        { epTypeId: 1, typeName: '学术引领' },
        { epTypeId: 2, typeName: '新闻资讯' }
      ],
      EditAddfile: "",
      createAddfile: "",
      hasFile: false,
      isShowGoodsListEdit: false,
      isShowProductListEdit: false,
      isShowFengEdit: false,
      isShowEditedit: false,
      EditForm: {},
      dialogEditFormVisible: false,
      isShowGoodsList: false,
      isShowProductList: false,
      isShowFeng: false,
      ProductList: [],
      GoodsList: [],
      isShow: false,
      Adaddfile: "",
      searchForm: {
        date: [],
        title: "",
        endTime: "",
        addTime: "",
        current: 1,
        size: 10,
        totalCount: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogCreateFormVisible: false,
      createForm: {},
      formLabelWidth: "120px",
      addfile: "",
      importFileUrl: this.GLOBAL.imgBaseUrl,
      isShowEdit: false,
      rules: {

        epTypeId: [
          { required: true, message: "请选择文章分类", trigger: "change" },
          // { validator: allNumValidate, trigger: 'blur' }
        ],
        isReferrer: [
          { required: true, message: "请输入文章排序", trigger: "change" },
          // { validator: allNumValidate, trigger: 'blur' }
        ],
        headImgUrl: [
          //   { required: true, message: "请输入文章封面", trigger: "change" },
          { validator: FengValidate, trigger: "change" },
        ],
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },

        ],
        content: [
          { required: true, message: "请输入文章详情", trigger: "change" },
          // { validator: allNumValidate, trigger: 'blur' }
        ],

      },
    };
  },
  created() {
    this.getList(this.currentPage, this.pageSize);
    // this.fenleilist();

  },
  methods: {
    goInfo(row) {
      this.$router.push({
        path: `/huanbaowenzhang/wenzhangxiangqing`,
        query: {
          jid: row.epArticleId,
        }
      })
    },

    //启用
    enable() {
      if (this.tableSelection.length != 1) {
        this.$message.error("请选中一行数据");
        return;
      }
      this.$confirm("确认要启用这条banner, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.banner
            .updateState({
              bannerIds: this.tableSelection[0].bannerId,
              status: 1, //状态 0禁用 1启用
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "启用成功",
                });
                this.getList(this.currentPage, this.pageSize);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消启用");
        });
    },
    //禁用
    disable() {
      if (this.tableSelection.length != 1) {
        this.$message.error("请选中一行数据");
        return;
      }
      this.$confirm("确认要禁用这条banner, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.banner
            .updateState({
              bannerIds: this.tableSelection[0].bannerId,
              status: 0, //状态 0禁用 1启用
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "禁用成功",
                });
                this.getList(this.currentPage, this.pageSize);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消禁用");
        });
    },


    editBanner(formName) {


      this.$api.agreement
        .updatewenzhang({
          content: this.EditForm.content,
          epArticleId: this.EditForm.epArticleId,
          headImgUrl: this.EditAddfile,
          isReferrer: this.EditForm.isReferrer,
          title: this.EditForm.title,
          epTypeId: this.EditForm.epTypeId
        })
        .then((d) => {
          if (d.code == 200) {
            this.$message.success("编辑文章信息成功");
            this.getList(this.currentPage, this.pageSize);
            this.dialogEditFormVisible = false;
          } else {
            this.$message.error(d.msg);
          }
        });




    },
    geEdittUrl(item) {
      // this.EditAddfile = item.data.url;
      this.EditAddfile = item;
      // console.log(this.Adaddfile);
      this.$message({
        type: "success",
        message: "图片上传成功",
      });
    },
    getProductList() {
      this.$api.store
        .getStoreList({
          pageno: 1,
          pagesize: 200,
        })
        .then((d) => {
          if (d.code == 1) {
            this.ProductList = d.data;
          }
        });
    },
    getGoodsList() {
      this.$api.goods.getStoreGoodsList().then((d) => {
        if (d.code == 1) {
          d.data.forEach((item) => {
            if (item.enable == 1) {
              this.GoodsList.push(item);
            }
          });

          // this.GoodsList = d.data;
        }
      });
    },
    getList(curr, page) {
      if (this.searchForm.date && this.searchForm.date.length == 2) {
        this.searchForm.startTime = this.format(this.searchForm.date[0]);
        this.searchForm.endTime = this.format(this.searchForm.date[1]);
      }
      this.$api.agreement
        .wenzhangilist({
          current: curr,
          size: page,
          addTime: this.searchForm.startTime,
          endTime: this.searchForm.endTime,
          title: this.searchForm.title
        })
        .then((d) => {
          if (d.code == 200) {
            this.tableData = d.data;
            this.total = d.totalCount;

          }
        });
    },
    getUrlAd(item) {
      this.createForm.addfile = item;
      // console.log(item);
      this.isShow = true;
      // console.log(this.Adaddfile);
      this.$message({
        type: "success",
        message: "图片上传成功",
      });
      // console.log(this.editimg);
    },
    showEdit() {
      if (this.createForm.bannerType == 1) {
        this.isShowEdit = false;
        this.isShowGoodsList = true;
        this.isShowProductList = false;
        this.isShowFeng = true;
      } else if (this.createForm.bannerType == 2) {
        this.isShowGoodsList = false;
        this.isShowEdit = false;
        this.isShowFeng = true;
        this.isShowProductList = true;
      } else if (this.createForm.bannerType == 3) {
        this.isShowGoodsList = false;
        this.isShowEdit = true;
        this.isShowFeng = true;
        this.isShowProductList = false;
      }
    },
    showEditType() {
      // console.log(this.EditForm.type);
      if (this.EditForm.type == 1) {
        this.isShowEditedit = false;
        this.isShowGoodsListEdit = true;
        this.isShowProductListEdit = false;
        this.isShowFengEdit = true;
      } else if (this.EditForm.type == 2) {
        this.isShowGoodsListEdit = false;
        this.isShowEditedit = false;
        this.isShowFengEdit = true;
        this.isShowProductListEdit = true;
      } else if (this.EditForm.type == 3) {
        this.isShowGoodsListEdit = false;
        this.isShowEditedit = true;
        this.isShowFengEdit = false;
        this.isShowProductListEdit = false;
      }
    },

    addBanner(formName) {

      this.$api.agreement.addwenzhang({
        content: this.createForm.content,
        headImgUrl: this.createForm.addfile,
        isReferrer: this.createForm.isReferrer,
        title: this.createForm.title,
        epTypeId: this.createForm.epTypeId


      }).then((d) => {
        if (d.code == 200) {
          this.dialogCreateFormVisible = false;
          this.$message.success("文章添加成功");
          this.$refs.child.clearText();
          this.hasFile = false;
          this.getList(this.currentPage, this.pageSize);
        } else {
          this.$message.error(d.msg);
        }
      });


    },
    clearText() {
      this.content = "";
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传活动封面大小不能超过 2MB!");
      }
      return isLt2M;
    },
    getUrl(item) {
      this.hasFile = true;
      // console.log(this.addfile);
      // this.addfile = item.data.url;
      this.createForm.addfile = item;
      this.createAddfile = item;
      // console.log(item);
      // this.isShow = true;
      this.$message({
        type: "success",
        message: "图片上传成功",
      });
      // console.log(this.editimg);
    },
    //打开新增模态框
    add() {

      this.createForm = {
        "epTypeId": '',
        "isReferrer": '',
        "headImgUrl": '',
        "title": '',
        "content": '',
      }

      this.isShowGoodsList = false;
      this.isShowEdit = false;
      this.isShowFeng = false;
      this.isShowProductList = false;
      // this.$refs.child.clearText();
      this.dialogCreateFormVisible = true;
    },
    //打开编辑模态框
    update() {
      if (this.tableSelection.length != 1) {
        this.$message.error('请选中一行数据');
        return
      }
      this.isShowEditedit = true;
      this.isShowFengEdit = true;
      this.isShowProductListEdit = false;
      this.isShowGoodsListEdit = false;
      this.EditForm = {

        typeName: this.tableSelection[0].typeName,
        epArticleId: this.tableSelection[0].epArticleId,
        isReferrer: this.tableSelection[0].isReferrer,
        title: this.tableSelection[0].title,
        content: this.tableSelection[0].content,
        epTypeId: this.tableSelection[0].epTypeId,


      };
      this.EditAddfile = this.tableSelection[0].headImgUrl;



      // console.log(12312312312, this.EditForm);
      this.dialogEditFormVisible = true;
    },
    //删除数据
    del() {
      if (this.tableSelection.length < 1) {
        this.$message.error('请选中一行数据');
        return
      }
      this.$confirm("确认要删除这条文章, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let ids = this.tableSelection.map(e => {
            return e.epArticleId
          })
          this.$api.agreement
            .delwenzhang({
              id: ids.join(','),
            })
            .then((d) => {
              if (d.code == 200) {
                this.$message({
                  type: "success",
                  message: "删除成功",
                });
                this.getList(this.currentPage, this.pageSize);
              } else {
                this.$message.error(d.msg);
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消启用");
        });
    },
    search() {
      this.getList(this.currentPage, this.pageSize);
    },
    handleReset() {
      this.searchForm = {
        title: "",
        endTime: "",
        addTime: "",
      }

      this.search();
    },
    exec(fun) {
      if (this[fun]) {
        this.funTit = fun;
        this[fun]();
      } else {
        this.$message.error("方法未定义");
      }
    },
    tableSelectionChange(val) {
      this.tableSelection = val;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList(this.currentPage, val);
      // eslint-disable-next-line no-console
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList(val, this.pageSize);
      // eslint-disable-next-line no-console
      // console.log(`当前页: ${val}`);
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  margin-top: 50px;
}
.img-feng {
  width: 120px;
  height: 120px;
}
.goods {
  width: 500px;
}
.icon {
  display: flex;
  justify-content: space-between;
  i {
    font-size: 25px;
  }
}
</style>
